import React, {useEffect, useState} from 'react';
import {Button, Table, Tag, Modal, Popover} from "antd";
import axios from "axios";
import {DeleteOutlined, EditOutlined, ExclamationCircleOutlined} from "@ant-design/icons";

const {confirm} = Modal
const RightList = () => {
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    axios.get("http://localhost:5000/rights?_embed=children")
      .then(r => {
        const list = r.data;
        list.forEach(item => {
          if (item.children.length === 0) {
            item.children = null;
          }
        })
        setDataSource(list);
      })
  }, [])

  const deleteMethod = (item) => {
    console.log(item)
    // 当前页面同步状态 + 后端同步
    if (item.grade === 1) {
      const newDateSource = dataSource.filter(data => data.id !== item.id)
      setDataSource(newDateSource);
      axios.delete(`http://localhost:5000/rights/${item.id}`)
        .then(r => {
          console.log(r)
        })
    } else {
      const list = dataSource.filter(data => data.id === item.rightId)
      list[0].children = list[0].children.filter(data => data.id !== item.id)
      setDataSource([...dataSource])
      axios.delete(`http://localhost:5000/children/${item.id}`)
        .then(r => {
          console.log(r)
        })
    }
  }

  const deleteConfirm = (item) => {
    confirm({
      title: "确定删除吗?",
      icon: <ExclamationCircleOutlined/>,
      content: "删除后数据不可恢复",
      okText: '确定删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        deleteMethod(item);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: (id) => <b>{id}</b>
    },
    {
      title: '权限名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      key: 'key',
      render: (key) => <Tag color={"orange"}>{key}</Tag>
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div>
            <Button
              danger={true}
              shape={"circle"}
              icon={<DeleteOutlined/>}
              onClick={() => deleteConfirm(item)}
            />
            <Popover
              content={<div>11111</div>}
              title={"配置项"}
              trigger={"click"}
            >
              <Button
                type={"primary"}
                shape={"circle"}
                icon={<EditOutlined/>}
              />
            </Popover>
          </div>
        )
      }
    },
  ];
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5
        }}
      />
    </div>
  );
};

export default RightList;